package com.achievement.service.impl;

import com.achievement.domain.bo.ArtProductBO;
import com.achievement.domain.dto.ArtProductDTO;
import com.achievement.domain.dto.author.ArtProductAuthorDTO;
import com.achievement.domain.entity.ArtProductEntity;
import com.achievement.domain.param.ArtProductParam;
import com.achievement.domain.vo.ArtProductVO;
import com.achievement.domain.vo.author.ArtProductAuthorVO;
import com.achievement.mapper.ArtProducMapper;
import com.achievement.mappings.ArtProductMapping;
import com.achievement.service.IAchievementFileService;
import com.achievement.service.IArtProductService;
import com.achievement.service.author.IArtProductAuthorService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.api.ApprovalApi;
import com.common.api.CommonFileApi;
import com.common.core.domain.AjaxResult;
import com.common.utils.DateUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BizProcessMessages;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 科研成果-艺术作品Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-27
 */
@Service
public class ArtProductServiceImpl  extends ServiceImpl<ArtProducMapper,ArtProductEntity> implements IArtProductService {
    @Autowired
    private ArtProductMapping mapping;

    @Autowired
    private IArtProductAuthorService authorService;

    @Autowired
    private IAchievementFileService fileService;

    @Autowired
    private ApprovalApi approvalApi;

    //通用文件api
    @Autowired
    private CommonFileApi fileApi;

    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;

    private final static String module_name = "艺术作品";

    @Override
    public List<ArtProductVO> selectArtProductList(ArtProductParam param) {
        QueryWrapper<ArtProductEntity> queryWrapper = new QueryWrapper<>();
        param.setPublicationDateStart(DateUtils.dateStrHandle(param.getPublicationDateStart(), param.getDateFormat(), "start"));
        param.setPublicationDateEnd(DateUtils.dateStrHandle(param.getPublicationDateEnd(), param.getDateFormat(), "end"));

        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getLeftCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getUnitId(), "unit_id");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getTypeId(), "type_id");

        queryWrapper.like(StringUtils.isNotEmpty(param.getAuthorpids()), "authorpids", param.getAuthorpids());

        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        List<ArtProductVO> list = this.baseMapper.selectArtProductList(param, queryWrapper);

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);

        list.stream().forEach(a -> {
            // 判断是否是审核人，并设置taskId
            String processInstanceId = a.getProcessInstanceId();
            if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                a.setTaskId(instanceTaskMap.get(processInstanceId));
                a.setIsAuditor(true);
            } else {
                a.setIsAuditor(false);
            }
        });
        return list;
    }

    /**
     * 左上方统计 通过，退回，待审核
     *
     * @param param
     */
    @Override
    public List<HashMap<String, Integer>> listStatistics(ArtProductParam param) {
        QueryWrapper<ArtProductEntity> queryWrapper = new QueryWrapper<>();
        param.setPublicationDateStart(DateUtils.dateStrHandle(param.getPublicationDateStart(), param.getDateFormat(), "start"));
        param.setPublicationDateEnd(DateUtils.dateStrHandle(param.getPublicationDateEnd(), param.getDateFormat(), "end"));

        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getLeftCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getUnitId(), "unit_id");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getTypeId(), "type_id");

        queryWrapper.like(StringUtils.isNotEmpty(param.getAuthorpids()), "authorpids", param.getAuthorpids());

        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        return this.baseMapper.listStatistics(param, queryWrapper);
    }

    /**
     * 艺术作品导出
     *
     * @param param
     */
    @Override
    public List<ArtProductVO> getListByConditions(ArtProductParam param) {
        QueryWrapper<ArtProductEntity> queryWrapper = new QueryWrapper<>();
        param.setPublicationDateStart(DateUtils.dateStrHandle(param.getPublicationDateStart(), param.getDateFormat(), "start"));
        param.setPublicationDateEnd(DateUtils.dateStrHandle(param.getPublicationDateEnd(), param.getDateFormat(), "end"));

        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getLeftCheckstatus(), "checkstatus");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getUnitId(), "unit_id");
        QueryWrapperUtils.dealInWrapper(queryWrapper, param.getTypeId(), "type_id");

        queryWrapper.like(StringUtils.isNotEmpty(param.getAuthorpids()), "authorpids", param.getAuthorpids());

        List<ArtProductVO> list = this.baseMapper.getListByExport(param, queryWrapper);
        return list;
    }

    @Override
    public ArtProductVO selectArtProductByID(String id) {
        ArtProductEntity entity = this.getById(id);
        List<ArtProductAuthorVO> authorVOList = authorService.getListByArtProductId(entity.getId());
        ArtProductVO vo = mapping.entity2Vo(entity);
        vo.setAuthorList(authorVOList);
        String fileIds = entity.getFileIds();
        if (StringUtils.hasText(fileIds)) {
            String[] fileIdArr = fileIds.split(",");
            List<Map<String,String>> fileInfo = fileService.getFileInfoByFileIds(fileIdArr);
            vo.setFileList(fileInfo);
        }

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        // 判断是否是审核人，并设置taskId
        String processInstanceId = vo.getProcessInstanceId();
        if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
            vo.setTaskId(instanceTaskMap.get(processInstanceId));
            vo.setIsAuditor(true);
        } else {
            vo.setIsAuditor(false);
        }
        return vo;
    }

    @Override
    public AjaxResult insertArtProduct(ArtProductDTO dto) {
        ArtProductBO bo = mapping.dto2Bo(dto);

//        List<ArtProductAuthorDTO> authorList=dto.getAuthorList().parallelStream().sorted(Comparator.comparing(ArtProductAuthorDTO::getOrderId)).collect(Collectors.toList());
        List<ArtProductAuthorDTO> authorList = dto.getAuthorList();

        ArtProductAuthorDTO authorDTO = authorList.get(0);//默认按orderId升序，取第一个
        bo.setFirstAuthorId(authorDTO.getPersonId());
        bo.setFirstAuthorName(authorDTO.getAuthorName());
        bo.setFirstAuthorAccount(authorDTO.getAuthorAccount());
        bo.setFirstAuthorSexid(authorDTO.getSexId());
        bo.setFirstAuthorEduDegreeId(authorDTO.getEduDegreeId());
        bo.setFirstAuthorTitleId(authorDTO.getTitleId());
        bo.setFirstAuthorEduLevelId(authorDTO.getEduLevelId());

        String authorpids = authorList.stream().map(ArtProductAuthorDTO::getPersonId).collect(Collectors.joining(";"));
        String authornames = authorList.stream().map(ArtProductAuthorDTO::getAuthorName).collect(Collectors.joining(";"));
        String authorunitids = authorList.stream().map(ArtProductAuthorDTO::getAuthorUnitId).collect(Collectors.joining(";"));

        bo.setAuthorpids(authorpids);
        bo.setAuthornames(authornames);
        bo.setAuthorunitids(authorunitids);
        bo.setAuthorNumber(authorList.size());

        ArtProductEntity entity = mapping.bo2Entity(bo);


        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                entity.setProcessInstanceId("0");
                entity.setCheckstatus(String.valueOf(submitType));
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                break;
            case 1: // 提交
                entity.setCheckstatus(String.valueOf(submitType));
                if (!(this.save(entity) && authorService.addBatch(authorList, entity.getId()))) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String processInstanceId = null;
                try {
                    //发起流程 业务状态由流程引擎更新
                    processInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                }

                return StringUtils.isEmpty(processInstanceId)
                        ? AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success((Object)entity.getId());
            default: // 处理 -1（暂存）及其他情况
                entity.setCheckstatus(String.valueOf(submitType));
                break;
        }

        boolean r = this.save(entity)
                && authorService.addBatch(authorList, entity.getId());
        return r ? AjaxResult.success((Object)entity.getId()) : AjaxResult.error(BizProcessMessages.SAVE_FAIL);

    }


    @Override
    public AjaxResult updateArtProduct(ArtProductDTO dto) {
        ArtProductBO bo = mapping.dto2Bo(dto);

//        List<ArtProductAuthorDTO> authorList=dto.getAuthorList().parallelStream().sorted(Comparator.comparing(ArtProductAuthorDTO::getOrderId)).collect(Collectors.toList());
        List<ArtProductAuthorDTO> authorList = dto.getAuthorList();

        ArtProductAuthorDTO authorDTO = authorList.get(0);//默认按orderId升序，取第一个
        bo.setFirstAuthorId(authorDTO.getPersonId());
        bo.setFirstAuthorName(authorDTO.getAuthorName());
        bo.setFirstAuthorAccount(authorDTO.getAuthorAccount());
        bo.setFirstAuthorSexid(authorDTO.getSexId());
        bo.setFirstAuthorEduDegreeId(authorDTO.getEduDegreeId());
        bo.setFirstAuthorTitleId(authorDTO.getTitleId());
        bo.setFirstAuthorEduLevelId(authorDTO.getEduLevelId());

        String authorpids = authorList.stream().map(ArtProductAuthorDTO::getPersonId).collect(Collectors.joining(";"));
        String authornames = authorList.stream().map(ArtProductAuthorDTO::getAuthorName).collect(Collectors.joining(";"));
        String authorunitids = authorList.stream().map(ArtProductAuthorDTO::getAuthorUnitId).collect(Collectors.joining(";"));

        bo.setAuthorpids(authorpids);
        bo.setAuthornames(authornames);
        bo.setAuthorunitids(authorunitids);
        bo.setAuthorNumber(authorList.size());

        ArtProductEntity entity = mapping.bo2Entity(bo);

        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                // 当前用户是否是审批人
                boolean isAuditor = dto.getIsAuditor();
                // 审批人直接审核（仅适用于提交类型2且为当前审核人的情况）
                if (isAuditor) {
                    if (this.updateById(entity)&& authorService.addBatch(authorList, entity.getId())) {
                        BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                        bta.setId(dto.getTaskId());
                        bta.setReason(SecurityUtils.getNickName() + "保存并通过");
                        try {
                            flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
                        } catch (Exception e) {
                            return AjaxResult.error(BizProcessMessages.SAVE_SUCCESS_APPROVE_FAIL, e.getMessage());
                        }

                        return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                    }
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                //处理非当前审批人保存并通过
                if (!dto.getCheckstatus().equals("2")){
                    entity.setProcessInstanceId("0");
                }
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                //只有管理员才会有非当前审核人的情况下有 "保存并提交"按钮,审核完后的结果只能是审核通过
                entity.setCheckstatus(String.valueOf(submitType));
                break;
            case 1:
                //暂存转提交
                if (!(this.updateById(entity)&& authorService.addBatch(authorList, entity.getId()))) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String returnProcessInstanceId = null;
                try {
                    returnProcessInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    return AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS, e.getMessage());
                }

                return StringUtils.isEmpty(returnProcessInstanceId)
                        ? AjaxResult.warn(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
            case -1: // 暂存
                return this.updateById(entity) && authorService.addBatch(authorList, entity.getId())
                        ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                        : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
            default:
                break;
        }

        return this.updateById(entity) && authorService.addBatch(authorList, entity.getId())
                ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                : AjaxResult.error(BizProcessMessages.SAVE_FAIL);

    }

    @Override
    public boolean deleteArtProductByIDs(List<String> ids) {

        List<ArtProductEntity> list = this.listByIds(ids);
        List<String> fileList = new ArrayList<>();
        //删除记录所携带的文件
        list.forEach(e -> {
            String fileIds = e.getFileIds();
            if (com.common.utils.StringUtils.isNotEmpty(fileIds)) {
                String[] split = fileIds.split(",");
                fileList.addAll(Arrays.asList(split));
            }
        });

        for (String fileId : fileList) {
            fileApi.delFile(fileId);
        }

        return this.removeByIds(ids) && authorService.batchRemoveByArtProductIds(ids);
    }

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {
        if (StringUtils.isEmpty(tableName) || StringUtils.isEmpty(businessId) || StringUtils.isEmpty(checkStatus))
            return;
        ArtProductEntity entity = new ArtProductEntity();
        entity.setId(businessId);
        entity.setCheckstatus(checkStatus);
        if ("2".equals(checkStatus)) {
            entity.setCheckdate(DateUtils.getTime());
            entity.setChecker(SecurityUtils.getNickName());
        }
        this.updateById(entity);
    }
}
